#include <iostream>
#include <string>
#include <unistd.h>
#include <pthread.h>
#include "MyThread.hpp"
#include "lock_guard.hpp"

using namespace std;

int ticket = 1000;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void *buyTicket(void *args)
{
    while (true)
    {
        { // 临界区
            lock_guard lg(&mutex);
            if (ticket > 0)
            {
                usleep(1000); // 模拟抢票所花的时间
                cout << "Get a ticket. Residue: [" << ticket-- << "]\n";
            }
            else
                return nullptr;
        } // 临界区
    }
}

int main()
{
    MyThread t1(1, buyTicket, (void *)"Thread-01");
    MyThread t2(2, buyTicket, (void *)"Thread-02");
    MyThread t3(3, buyTicket, (void *)"Thread-02");
    t1.run();
    t2.run();
    t3.run();
    t1.join();
    t2.join();
    t3.join();
    cout << "The rest of ticket: " << ticket << endl;
    return 0;
}